<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Tools extends CI_Controller {
	public function upload() {
		$p_data = $this->input->post();
		if ( stristr($this->input->user_agent(),'Shockwave Flash') || stristr($this->input->user_agent(),'Adobe Flash Player') ) {

			$session = $this->db->select()->from('sessions')->where('session_id', $p_data['session'])->get()->row_array();
			if (sizeof($session) > 0) {
				$sesdata = unserialize($session['user_data']);
				if ($sesdata['group'] == 'admin' || $sesdata['group'] == 'moderator' || $p_data['secure'] != "") {
					if (!is_dir('./uploads/uploadify/'.$p_data['random'])) {
						mkdir('./uploads/uploadify/'.$p_data['random']);
						mkdir('./uploads/uploadify/'.$p_data['random'].'/small');
						mkdir('./uploads/uploadify/'.$p_data['random'].'/middle');
						chmod('./uploads/uploadify/'.$p_data['random'], 0777);
						chmod('./uploads/uploadify/'.$p_data['random'].'/small', 0777);
						chmod('./uploads/uploadify/'.$p_data['random'].'/middle', 0777);
					}

					$config['upload_path'] = './uploads/uploadify/'.$p_data['random'].'/';
					$config['allowed_types'] = 'gif|jpg|png';
					$config['max_size']	= '2048';
					$config['max_width']  = ($p_data['max_width']?intval($p_data['max_width']):2000);
					$config['max_height']  = ($p_data['max_height']?intval($p_data['max_height']):2000);
					$config['encrypt_name']  = true;
					$config['remove_spaces']  = true;

					$max_small_height = 150;
					$max_small_width = 150;
					$max_middle_height = 250;
					$max_middle_width = 250;

					if ($p_data['max_small_height'] != "") $max_small_height = $p_data['max_small_height'];
					if ($p_data['max_small_width'] != "") $max_small_width = $p_data['max_small_width'];
					if ($p_data['max_middle_height'] != "") $max_middle_height = $p_data['max_middle_height'];
					if ($p_data['max_middle_width'] != "") $max_middle_width = $p_data['max_middle_width'];

					$this->load->library('upload', $config);

					if (!$this->upload->do_upload('Filedata')) {
						echo $this->upload->display_errors();
					} else {
						$file = $this->upload->data();
						$this->load->library('thumbnail');
						$im = getimagesize($file['full_path']);
						if ($im[0] <= $config['max_width'] && $im[1] <= $config['max_height']) {
							if ($im[0] > 1000 || $im[1] > 1000) {
								$this->thumbnail->output($file['full_path'], $file['full_path'], array('width' => '1000', 'height' => '1000', 'method' => THUMBNAIL_METHOD_SCALE_MAX, 'halign'  => THUMBNAIL_ALIGN_CENTER, 'valign'  => THUMBNAIL_ALIGN_CENTER));
							}
							if ($p_data['small_required'] == "true") {
								$this->thumbnail->output($file['full_path'], './uploads/uploadify/'.$p_data['random'].'/small/'.$file['file_name'], array('width' => $max_small_width, 'height' => $max_small_height, 'method' => ($p_data['small_type'] == 'min'?THUMBNAIL_METHOD_SCALE_MIN:THUMBNAIL_METHOD_SCALE_MAX), 'halign'  => THUMBNAIL_ALIGN_CENTER, 'valign'  => THUMBNAIL_ALIGN_CENTER));
							} else {
								if ($im[0] > $max_small_width || $im[1] > $max_small_height) {
									$this->thumbnail->output($file['full_path'], './uploads/uploadify/'.$p_data['random'].'/small/'.$file['file_name'], array('width' => $max_small_width, 'height' => $max_small_height, 'method' => THUMBNAIL_METHOD_SCALE_MAX, 'halign'  => THUMBNAIL_ALIGN_CENTER, 'valign'  => THUMBNAIL_ALIGN_CENTER));
								} else {
									copy($file['full_path'], './uploads/uploadify/'.$p_data['random'].'/small/'.$file['file_name']);
								}
							}
							if ($p_data['middle_required'] == "true") {
								$this->thumbnail->output($file['full_path'], './uploads/uploadify/'.$p_data['random'].'/middle/'.$file['file_name'], array('width' => $max_middle_width, 'height' => $max_middle_height, 'method' => ($p_data['middle_type'] == 'min'?THUMBNAIL_METHOD_SCALE_MIN:THUMBNAIL_METHOD_SCALE_MAX), 'halign'  => THUMBNAIL_ALIGN_CENTER, 'valign'  => THUMBNAIL_ALIGN_CENTER));
							} else {
								if ($im[0] > $max_middle_width || $im[1] > $max_middle_height) {
									$this->thumbnail->output($file['full_path'], './uploads/uploadify/'.$p_data['random'].'/middle/'.$file['file_name'], array('width' => $max_middle_width, 'height' => $max_middle_height, 'method' => THUMBNAIL_METHOD_SCALE_MAX, 'halign'  => THUMBNAIL_ALIGN_CENTER, 'valign'  => THUMBNAIL_ALIGN_CENTER));
								} else {
									copy($file['full_path'], './uploads/uploadify/'.$p_data['random'].'/middle/'.$file['file_name']);
								}
							}
							$im = getimagesize('./uploads/uploadify/'.$p_data['random'].'/small/'.$file['file_name']);
							$padding = round((150 - $im[1]) / 2);
							echo "10#".$file['file_name']."#".$padding."#".str_replace("/", ":", '/uploads/uploadify/'.$p_data['random'].'/'.$file['file_name']);
						} else {
							echo "Превышены допустимые размеры изображения";
						}
					}
				} else {
					die('Session closed by code #3: нет прав для загрузки изображений'); // auth
				}
			} else{
				die('Session closed by code #2: из базы данных не получены данные по сессии.<br />'.print_r($session, true).' <br /> входные данные: '.print_r($p_data, true)); // sizeof session
			}
		} else {
			die('Session closed by code #1: прямой доступ к скрипту'); // client
		}
	}
	function delete() {
		$p_data = $this->input->post();
		if (mb_substr_count($p_data['file'], 'user_images') <= 0) {
			if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) die('unathorized');
		}
		$inf = explode(":", $p_data['file']);
		if ($inf[2] == "uploadify") {

			// я псих))

			$path = ".".str_replace(":", "/", $p_data['file']);
			unlink($path);
			$inf[5] = $inf[4];
			$inf[4] = "small";
			$path = ".".implode("/", $inf);
			unlink($path);
			$inf[4] = "middle";
			$path = ".".implode("/", $inf);
			unlink($path);
		} else {
			if ($inf[0] == "one") {
				if ($inf[2] == 'catalog_parents') {
					$key = 'parent';
				} else {
					$key = $inf[2];
				}
				if ($inf[2] == 'catalog_brands') {
					$key = 'brand';
				} else {
					$key = $inf[2];
				}
				$this->db->update($inf[2], array($key.'_image' => ''), array($key.'_id' => $inf[3]));
				array_shift($inf);
				$path = "./".implode("/", $inf);
				unlink($path);
				$inf[4] = $inf[3];
				$inf[3] = "small";
				$path = "./".implode("/", $inf);
				unlink($path);
				$inf[3] = "middle";
				$path = "./".implode("/", $inf);
				unlink($path);
			} elseif ($inf[0] == "multi") {
				if ($inf[2] == 'catalog_items') {
					$table = 'catalog_images';
					$key = 'photo';

					$check = $this->db->select()->from('catalog_images')->where('photo_file', $inf[4])->get()->row_array();
					if ($check['photo_main'] == 1) {
						$newmain = $this->db->select()->from('catalog_images')->where('photo_item', $check['photo_item'])->where('photo_file != ', $inf[4])->get()->row_array();
						if (sizeof($newmain) > 0) {
							$this->db->where('photo_id', $newmain['photo_id'])->update('catalog_images', array('photo_main' => '1'));
						}
					}
				} elseif ($inf[2] == 'user_images') {
					$table = 'user_images';
					$key = 'photo';
				} else {
					$table = $inf[2];
					$key = $inf[2];
				}
				$this->db->delete($table, array($key.'_file' => $inf[4]));
				array_shift($inf);
				$path = "./".implode("/", $inf);
				unlink($path);
				$inf[4] = $inf[3];
				$inf[3] = "small";
				$path = "./".implode("/", $inf);
				unlink($path);
				$inf[3] = "middle";
				$path = "./".implode("/", $inf);
				unlink($path);
			}
		}
		echo "ok";
	}
	public function install() {
//		chmod($_SERVER['DOCUMENT_ROOT']."/data/js/fckeditor", 0777);

		$htaccess = "require valid-user
allow from all
<Limit GET POST>
	require valid-user
</Limit>
AuthType Basic
AuthName 'jaguarsoft.ru'
AuthUserFile ".$_SERVER['DOCUMENT_ROOT']."/data/js/fckeditor/.htpasswd";


		$h = fopen($_SERVER['DOCUMENT_ROOT']."/data/js/fckeditor/.htaccess", "w");
		fwrite($h, $htaccess);
		fclose($h);

//		chmod($_SERVER['DOCUMENT_ROOT']."/data/js/fckeditor", 0644);

		redirect('admin/');
	}
	function video() {
		$rel = $this->input->post('rel');
		$this->load->view('video/'.$rel);
	}
	function cache() {
		$this->db->cache_delete_all();
		$this->session->set_flashdata('msg', 'Кэш скинут');
		redirect($_SERVER['HTTP_REFERER']);
	}
}